package org.tamal.jsf;

import java.util.Map;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.tamal.SessionKey;

/**
 * This listener forces AppEngine to save the session in the data-store.
 * @author Tamal Kanti Nath
 */
public final class SessionListener implements PhaseListener {

    private static final long serialVersionUID = -1079141112326706660L;

    @Override
    public void afterPhase(PhaseEvent event) {
        String view = event.getFacesContext().getViewRoot().getViewId();
        Map<String, Object> sessionMap = event.getFacesContext()
                .getExternalContext().getSessionMap();
        String viewNeedSession = System.getProperty("viewNeedSession");
        if (viewNeedSession == null) {
            return;
        }
        for (String bean : viewNeedSession.split(",")) {
            if (view.equals(bean)) {
                sessionMap.put(SessionKey.CURRENT_TIME.name(),
                        System.currentTimeMillis());
            }
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        // Empty
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }

}
